/*
 * Copyright (c) 2020-2022. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.depsea.log.notification.matcher;

import org.apache.commons.lang3.ClassUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Wang Chengwei
 * @since 1.0.0 [2022/12/3 17:20]
 */
public class DefaultIgnoreExceptionMatcher implements IgnoreExceptionMatcher {

    private final List<Class<? extends Throwable>> ignoreExceptions;

    public DefaultIgnoreExceptionMatcher(List<Class<? extends Throwable>> ignoreExceptions) {
        this.ignoreExceptions = ignoreExceptions;
    }

    public DefaultIgnoreExceptionMatcher(Class<? extends Throwable>... ignoreExceptions) {
        this.ignoreExceptions = new ArrayList<>();
        this.ignoreExceptions.addAll(Arrays.asList(ignoreExceptions));
    }

    @Override
    public boolean matches(Exception ex) {
        if (CollectionUtils.isEmpty(ignoreExceptions)) {
            return false;
        }
        for (Class<? extends Throwable> ignoreException : ignoreExceptions) {
            if (ClassUtils.isAssignable(ignoreException, ex.getClass())) {
                return true;
            }
        }
        return false;
    }

    public void addIgnoreExceptions(Class<? extends Throwable> ignoreException) {
        this.ignoreExceptions.add(ignoreException);
    }
}
